/*
 * @Author: guandeshen 295570679@qq.com
 * @Date: 2024-05-08 23:51:45
 * @LastEditors: guandeshen 295570679@qq.com
 * @LastEditTime: 2024-08-31 01:38:53
 * @FilePath: /task-admin/src/plugins/permission.ts
 * @Description:
 *
 * Copyright (c) 2024 by ${git_name_email}, All Rights Reserved.
 */
import {
  NavigationGuardNext,
  RouteLocationNormalized,
  RouteRecordRaw,
} from "vue-router";

import router from "@/router";
import { useUserStore, usePermissionStore } from "@/store";
import NProgress from "@/utils/nprogress";
import { TOKEN_KEY } from "@/enums/CacheEnum";

export function setupPermission() {
  // 白名单路由
  const whiteList = ["/login"];

  router.beforeEach(async (to, from, next) => {
    NProgress.start();
    const hasToken = localStorage.getItem(TOKEN_KEY);
    if (hasToken) {
      if (to.path === "/login") {
        // 如果已登录，跳转首页
        next({ path: "/" });
        NProgress.done();
      } else {
        const userStore = useUserStore();
        const hasRoles =
          userStore.user.roles && userStore.user.roles.length > 0;

        //   const hasRoles = true;
        // const roles = ["ADMIN"];
        // const permissionStore = usePermissionStore();
        // const dynamicRoutes = await permissionStore.generateRoutes(roles);
        // dynamicRoutes.forEach((route: RouteRecordRaw) =>
        //   router.addRoute(route)
        // );

        if (hasRoles) {
          // 未匹配到任何路由，跳转404
          if (to.matched.length === 0) {
            from.name ? next({ name: from.name }) : next("/404");
          } else {
            // 如果路由参数中有 title，覆盖路由元信息中的 title
            const title =
              (to.params.title as string) || (to.query.title as string);
            if (title) {
              to.meta.title = title;
            }
            next();
          }
        } else {
          const permissionStore = usePermissionStore();
          try {
            await userStore.getUserInfo();
            const roles = ["ADMIN"];
            const dynamicRoutes = await permissionStore.generateRoutes(roles);
            dynamicRoutes.forEach((route: RouteRecordRaw) =>
              router.addRoute(route)
            );
            next({ ...to, replace: true });
          } catch (error) {
            // 移除 token 并重定向到登录页，携带当前页面路由作为跳转参数
            await userStore.resetToken();
            redirectToLogin(to, next);
            NProgress.done();
          }
        }
      }
    } else {
      // 未登录可以访问白名单页面
      if (whiteList.indexOf(to.path) !== -1) {
        next();
      } else {
        next(`/login?redirect=${to.path}`);
        NProgress.done();
      }
    }
  });

  /** 重定向到登录页 */
  function redirectToLogin(
    to: RouteLocationNormalized,
    next: NavigationGuardNext
  ) {
    const params = new URLSearchParams(to.query as Record<string, string>);
    const queryString = params.toString();
    const redirect = queryString ? `${to.path}?${queryString}` : to.path;
    next(`/login?redirect=${encodeURIComponent(redirect)}`);
  }

  router.afterEach(() => {
    NProgress.done();
  });
}
